﻿#region Copyright Description
/**********************************************************
(C) Copyright 谢文明. 2011
文件名      : OConfig.cs
功能        : 配置管理类
作者        : xiewenming
完成日期    : 2011-7-15
版本        : debug
************************************************************/
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Data;
using System.Web.UI.WebControls;



    /// <summary>
    /// 配置管理类
    /// </summary>
    public class OConfig
    {
        /// <summary>
        /// 获取系统使用的数据库类型
        /// </summary>
        /// <returns>数据库类型</returns>
        public static DBType SysDBType
        {
            get
            {
                string type = System.Configuration.ConfigurationManager.AppSettings["DBType"].ToString();

                DBType dbtype = DBType.SQL;
                switch (type.ToUpper())
                {
                    case "ACCSS":
                        dbtype = DBType.ACCESS;
                        break;

                    case "SQL":
                        dbtype = DBType.SQL;
                        break;


                    case "ORACLE":
                        dbtype = DBType.ORACLE;
                        break;
                }

                return dbtype;
            }
        }

        /// <summary>
        /// 获取数据连接字符串
        /// </summary>
        /// <returns>数据库连接字符串</returns>
        public static string DBConnection
        {
            get
            {
                return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString.ToString();
            }
        }
        /// <summary>
        /// 缓存服务器IP地址
        /// </summary>
        public static string WebCachedServer
        {
            get
            {
                return System.Configuration.ConfigurationManager.ConnectionStrings["webCachedServer"].ConnectionString.ToString();
            }
        }
        /// <summary>
        /// 获取唯一标识符
        /// </summary>
        /// <returns>标识符</returns>
        public static string GetGUID()
        {
            return System.Guid.NewGuid().ToString("N");
        }

        /// <summary>
        /// 获取系统当前使用SQL脚本文件名称
        /// </summary>
        /// <returns></returns>
        public static string XMLFileName
        {
            get
            {
                DBType type = SysDBType;

                string fileName = "SysSQL_";
                switch (type)
                {
                    case DBType.ACCESS:
                        fileName += "Sql.xml";
                        break;

                    case DBType.ORACLE:
                        fileName += "Oracle.xml";
                        break;

                    case DBType.SQL:
                        fileName += "Sql.xml";
                        break;

                }

                return fileName;
            }
        }
        /// <summary>
        /// 获取数据的分页的起止行号
        /// </summary>
        /// <param name="tabName">表名称</param>
        /// <param name="condition">条件</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageRowCount">每一页显示的行数</param>
        /// <param name="startIndex">开始行号</param>
        /// <param name="totalPage">总页数</param>
        /// <param name="endIndex">结束行号</param>
        /// <param name="totalRow">数据总行数</param>
        public static void GetStartRowNum(string tabName, string condition, int pageIndex, int pageRowCount, out int startIndex, out int endIndex, out int totalPage, out int totalRow)
        {
            startIndex = 0;
            totalPage = 0;
            totalRow = 0;
            endIndex = 0;
            try
            {
                IDBAccess DB = DBFactory.GetDBAccess(SysDBType, DBConnection);
                if (condition.Length > 0)
                {
                    if (!condition.Trim().ToLower().StartsWith("where"))
                        condition = "where " + condition;
                }
                string sql = "select count(*) from " + tabName + " " + condition;
                object obj = DB.ExecuteScalar("select count(*) from " + tabName + " " + condition, CommandType.Text, null);

                if (null != obj)
                {
                    totalRow = Convert.ToInt32(obj);  // 总行数
                    totalPage = totalRow / pageRowCount + ((totalRow % pageRowCount > 0) ? 1 : 0); // 总页数
                    if (pageIndex > 0)
                    {
                        pageIndex -= 1;

                    }

                    startIndex = pageIndex * pageRowCount + ((pageIndex > 0) ? 1 : 0);
                    endIndex = startIndex + pageRowCount - ((pageIndex > 0) ? 1 : 0);
                }
            }
            catch (Exception exp)
            {
            }
        }
        /// <summary>
        /// 获取数据的分页的起止行号
        /// </summary>
        /// <param name="tabName">表名称</param>
        /// <param name="condition">条件</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageRowCount">每一页显示的行数</param>
        /// <param name="startIndex">开始行号</param>
        /// <param name="totalPage">总页数</param>
        /// <param name="endIndex">结束行号</param>
        /// <param name="totalRow">数据总行数</param>
        public static void GetStartRowNum(string sql, int pageIndex, int pageRowCount, out int startIndex, out int endIndex, out int totalPage, out int totalRow)
        {
            startIndex = 0;
            totalPage = 0;
            totalRow = 0;
            endIndex = 0;
            try
            {
                IDBAccess DB = DBFactory.GetDBAccess(SysDBType, DBConnection);
               
                object obj = DB.ExecuteScalar(sql, CommandType.Text, null);

                if (null != obj)
                {
                    totalRow = Convert.ToInt32(obj);  // 总行数
                    totalPage = totalRow / pageRowCount + ((totalRow % pageRowCount > 0) ? 1 : 0); // 总页数
                    if (pageIndex > 0)
                    {
                        pageIndex -= 1;

                    }

                    startIndex = pageIndex * pageRowCount + ((pageIndex > 0) ? 1 : 0);
                    endIndex = startIndex + pageRowCount - ((pageIndex > 0) ? 1 : 0);
                }
            }
            catch (Exception exp)
            {
            }
        }

        public static void GetStartRowNumGroup(int rowCount, int pageIndex, int pageRowCount, out int startIndex, out int endIndex, out int totalPage, out int totalRow)
        {
            startIndex = 0;
            totalPage = 0;
            totalRow = 0;
            endIndex = 0;
            try
            {
                totalRow = rowCount;  // 总行数




                totalPage = totalRow / pageRowCount + ((totalRow % pageRowCount > 0) ? 1 : 0); // 总页数




                if (pageIndex > 0)
                {
                    pageIndex -= 1;

                }

                startIndex = pageIndex * pageRowCount + ((pageIndex > 0) ? 1 : 0);
                endIndex = startIndex + pageRowCount - ((pageIndex > 0) ? 1 : 0);

            }
            catch (Exception exp)
            {
            }
        }


        /// <summary>
        /// 关闭窗体，刷新打开的父窗体
        /// </summary>
        /// <param name="ControlName">父窗体刷新按钮的名称</param>
        /// <param name="Page">当前操作的页面</param>
        public static void RefreshSourceWindow(string ControlName, System.Web.UI.Page Page)
        {
            string script = "";
            script += "<script language='javascript'>";
            script += "alert('数据保存成功');";
            script += "  opener.__doPostBack('" + ControlName + "','');";
            script += "  this.close();";
            script += "</script>";
            Page.RegisterStartupScript("RefreshSourceWindowAndCloseMe", script);

        }
        public static void RefreshSourceWindowDontColse(string ControlName, System.Web.UI.Page Page,string url)
        {
            string script = "";
            script += "<script language='javascript'>";
            script += "alert('数据保存成功');";
            script += "  opener.__doPostBack('" + ControlName + "','');";
          script += "  window.location='"+url+"';";
            script += "</script>";
            Page.RegisterStartupScript("RefreshSourceWindowAndCloseMe", script);

        }
        /// <summary>
        /// 弹出保存失败的对话框
        /// </summary>
        /// <param name="Page"></param>
        public static void AlertFaileSourceWindow(string alertInfo, System.Web.UI.Page Page)
        {
            string script = "";
            script += "<script language='javascript'>";
            script += "alert('" + alertInfo + "');";
            script += "</script>";
            Page.RegisterStartupScript("RefreshSourceWindowAndCloseMe", script);

        }
        /// <summary>
        /// 弹出保存失败的对话框
        /// </summary>
        /// <param name="Page"></param>
        public static void AlertFaileSourceWindowAndClose(string alertInfo, System.Web.UI.Page Page)
        {
            string script = "";
            script += "<script language='javascript'>";
            script += "alert('" + alertInfo + "');window.close();";
            script += "</script>";
            Page.RegisterStartupScript("RefreshSourceWindowAndCloseMe", script);

        }

        /// <summary>
        /// 弹出对话框，父窗体重刷，关闭本窗体


        /// </summary>
        /// <param name="alertInfo"></param>
        /// <param name="Page"></param>
        /// <param name="strHref"></param>
        public static void AlertSourceWindowAndCloseOpenerReload(string alertInfo, System.Web.UI.Page Page, string strHref)
        {
            string script = "";
            script += "<script language='javascript'>";
            script += "alert('" + alertInfo + "');opener.location.href='" + strHref + "'; window.close();";
            script += "</script>";
            Page.RegisterStartupScript("RefreshSourceWindowAndCloseMe", script);

        }

        /// <summary>
        /// 弹出保存失败的对话框
        /// </summary>
        /// <param name="Page"></param>
        public static void AlertFaileSourceWindow(string alertInfo, System.Web.UI.Page Page, string controlName)
        {
            string script = "";
            script += "<script language='javascript'>";
            script += "alert('" + alertInfo + "');";
            script += "  var control = document.getElementById('";
            script += controlName + "' );";
            script += "  if( control != null ){control.focus();}";
            script += "</script>";

            Page.RegisterStartupScript("RefreshSourceWindowAndCloseMe", script);

        }
        /// <summary>
        /// 弹出保存失败的对话框
        /// </summary>
        /// <param name="Page"></param>
        public static void AlertFaileSourceWindowSetTab(string alertInfo, System.Web.UI.Page Page, string controlName,string tabCount)
        {
            string script = "";
            script += "<script language='javascript'>";
            script += "alert('" + alertInfo + "');";
            script += "setTab(" + tabCount + ");";
            script += "  var control = document.getElementById('";
            script += controlName + "' );";
            script += "  if( control != null ){control.focus();}";
            script += "</script>";

            Page.RegisterStartupScript("RefreshSourceWindowAndCloseMe", script);

        }


        /// <summary>
        /// 删除记录时候的提示语
        /// </summary>
        /// <param name="alertInfo"></param>
        /// <returns></returns>
        public static string DeleteInofAlert(string alertInfo)
        {
            return "你确认要删除序号为【" + alertInfo + "】的记录吗？";
        }
        /// <summary>
        /// 弹出的新窗口在显示屏中居中显示的方法
        /// </summary>author：mornrouse
        /// <param name="intNewPageWidth">新窗口的宽度</param>
        /// <param name="intNewPageHeight">新窗口的高度度</param>
        /// <param name="strNewPageUrl">要打开的页面的地址，包括参数等，如add.aspx?id=123&currentPage=page456</param>
        /// <returns></returns>
        public static string AlertPageInWindowCenter(int intNewPageWidth, int intNewPageHeight, string strNewPageUrl)
        {
            string strFunction = "<script>";
            strFunction += "var NewPageWidth = window.screen.width  / 2 - " + intNewPageWidth + "  / 2;";
            //此处加上50个像素的目的是去除窗口下面的导航高度
            strFunction += "var NewPageHeight = window.screen.height / 2 - " + (intNewPageHeight + 50) + " / 2;if(NewPageHeight<0){NewPageHeight=0};";
            strFunction += "window.open('" + strNewPageUrl + "','','height=" + intNewPageHeight + ",width=" + intNewPageWidth + ",top='+NewPageHeight+'px,left='+NewPageWidth+'px'); </script>";
            return strFunction;
        }
       
        /// <summary>
        /// 数据导出excel的方法



        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <param name="gvInfo">数据窗口</param>
        /// <param name="excelPage">导出数据的web页面</param>
        public static void WriteToExcelFromDataGrid(string fileName, GridView gvInfo, System.Web.UI.Page excelPage)
        {

            excelPage.Response.Clear();
            excelPage.Response.Buffer = true;
            excelPage.Response.Charset = "gb2312";
            //下面这行很重要， attachment 参数表示作为附件下载，您可以改成 online在线打开 

            //filename=FileFlow.xls 指定输出文件的名称，注意其扩展名和指定文件类型相符，可以为：.doc 　　 .xls 　　 .txt 　　.htm　　 

            excelPage.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName) + ".xls");
            //2010-03-05 宋永斌修改(原因：Excel导出乱码)
            //excelPage.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            excelPage.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");


            //Response.ContentType指定文件类型 可以为application/ms-excel 　　 application/ms-word 　　 application/ms-txt 　　 application/ms-html 　　 或其他浏览器可直接支持文档　
            excelPage.Response.ContentType = "application/ms-excel";

            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            gvInfo.RenderControl(oHtmlTextWriter);
            //this 表示输出本页，你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件　　
            excelPage.Response.Write(oStringWriter.ToString());
            excelPage.Response.End();

   

        }
        /// <summary>
        /// 数据导出excel的方法 
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <param name="gvInfo">数据窗口</param>
        /// <param name="excelPage">导出数据的web页面</param>
        public static void WriteToExcel(string fileName, GridView gvInfo, System.Web.UI.Page excelPage)
        {

            excelPage.Response.Clear();
            excelPage.Response.Buffer = true;
            excelPage.Response.Charset = "gb2312";
            //下面这行很重要， attachment 参数表示作为附件下载，您可以改成 online在线打开 

            //filename=FileFlow.xls 指定输出文件的名称，注意其扩展名和指定文件类型相符，可以为：.doc 　　 .xls 　　 .txt 　　.htm　　 

            excelPage.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            //2010-03-05 宋永斌修改(原因：Excel导出乱码)
            //excelPage.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            excelPage.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");


            //Response.ContentType指定文件类型 可以为application/ms-excel 　　 application/ms-word 　　 application/ms-txt 　　 application/ms-html 　　 或其他浏览器可直接支持文档　
            excelPage.Response.ContentType = "application/ms-excel";

            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            gvInfo.RenderControl(oHtmlTextWriter);
            //this 表示输出本页，你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件　　
            excelPage.Response.Write(oStringWriter.ToString());
            excelPage.Response.End();

          

        }


        /// <summary>
        /// 字符串长度(按字节算)
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int StrLength(string str)
        {
            int len = 0;
            byte[] b;
            for (int i = 0; i < str.Length; i++)
            {
                b = Encoding.Default.GetBytes(str.Substring(i, 1));
                if (b.Length > 1)
                    len += 2;
                else
                    len++;
            }
            return len;
        }

        /// <summary>
        /// 截取指定长度字符串(按字节算)
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string StrCut(string str, int length)
        {
            int len = 0;
            byte[] b;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < str.Length; i++)
            {
                b = Encoding.Default.GetBytes(str.Substring(i, 1));
                if (b.Length > 1)
                    len += 2;
                else
                    len++;
                if (len >= length)
                    break;
                sb.Append(str[i]);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 判断当前添加的或者编辑的记录是否存在
        /// </summary>
        /// <param name="tableName">操作的数据库表名称</param>
        /// <param name="checkColumn">检查的列字段</param>
        /// <param name="checkColumnValue">判断的字段对应的用户输入的内容</param>
        /// <param name="isAdd">是否是添加状态</param>
        /// <param name="EditID">数据编辑的时候的主键值</param>
        /// <param name="keyColumn">数据库主键字段</param>
        /// <returns></returns>
        public bool CheckInfoExistOrNot(string tableName, string checkColumn,string checkColumnValue, bool isAdd, string EditID,string keyColumn)
        {
            int result = 0;
            DBType dbType = OConfig.SysDBType;
            IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);
            StringBuilder strSql = new StringBuilder();
            try
            {
                if (isAdd)
                {
                    strSql.Append("select count(*) from " + tableName + " where " + checkColumn + "='" + checkColumnValue + "' ");
                }
                else
                {
                    strSql.Append("select count(*) from " + tableName + " where " + checkColumn + "='" + checkColumnValue + "' and " + keyColumn + "!='" + EditID + "'");
                }
                result = Convert.ToInt32(DB.ExecuteScalar(strSql.ToString(), CommandType.Text, null));
                if (result > 0)
                {
                    return false;//存在
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                return true;
            }
        }
        /// <summary>
        /// 根据表的编码读取该表高级查询的字段信息


        /// </summary>
        /// <param name="tableCode">表的编码</param>
        /// <returns>根据表的编码读取该表高级查询的字段信息</returns>
        public static DataSet SelctAdvancedSearchColumn(string tableCode)
        {
            DataSet ds = new DataSet();
            bool flag = false;
            DBType dbType = OConfig.SysDBType;
            IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);
            string sqlCommand = "select * from tl_searchcolumn where tableName='" + tableCode + "' order by orderID";
            ds = DB.ExecuteDataSet(sqlCommand, CommandType.Text, null);
            return ds;
        }
        /// <summary>
        /// 判断用户是否有具体模块的功能权限，如添加、编辑、删除操作等等


        /// </summary>
        /// <param name="userID">用户的ID</param>
        /// <param name="menucode">菜单编码</param>
        /// <param name="cfunction">功能编码</param>
        /// <returns></returns>
        public static bool CheckUserHaveFunctionRight(string userID, string menucode, string cfunction)
        {
            DataSet ds = new DataSet();
            DBType dbType = OConfig.SysDBType;
            IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);
            //加载SQL语句的信息


            string sqlCommand = "select a.menucode from ts_menu a,ts_rolemenu b ,ts_user c,ts_roleFunction d,ts_userVSrole e  where e.roleID=b.roleID and    b.menuCode=a.menuCode  and b.roleID=d.roleID  and c.userID=@userID and d.menuCode=@menucode and c.userid=e.userid  and d.cFunctionCode=@cfunction";

            IDbDataParameter[] paras = DB.CreateDBParameter(dbType,
                   new string[3] { "menucode", "cfunction", "userID" },
                   new DbType[3] { DbType.String, DbType.String, DbType.String },
                   new object[3] { menucode, cfunction, userID });

            ds = DB.ExecuteDataSet(sqlCommand, CommandType.Text, paras);
            if (ds == null)
            {
                return false;
            }
            else
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 判断用户是否有当前页面的访问权限
        /// </summary>
        /// <param name="userID">用户的ID</param>
        /// <param name="modelCode">模块的编码</param>
        /// <returns>用户是否有当前页面的访问权限</returns>
        public static bool CheckUserHavePageRight(string userID, string modelCode)
        {
            bool flag = false;
            DBType dbType = OConfig.SysDBType;
            IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);
            string sqlCommand = "select a.menuCode from ts_menu a,ts_rolemenu b ,ts_user c,ts_userVSrole e  where e.roleID=b.roleID and b.menuCode=a.menuCode and c.userid=e.userid and c.userID=@userID and a.menuCode=@menuCode";
            IDbDataParameter[] para = DB.CreateDBParameter(dbType,
                   new string[2] { "userID", "menucode" },
                   new DbType[2] { DbType.String, DbType.String },
                   new object[2] { userID, modelCode });
            DataSet ds = new DataSet();
            ds = DB.ExecuteDataSet(sqlCommand, CommandType.Text, para);
            if (ds != null)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    flag = true;
                }
            }
            return flag;
        }


        public static bool CheckPerm(string userid, string menucode)
        {
            DBType dbType = OConfig.SysDBType;
            IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);
            bool flag = false;
            string sqlCommand = " select * from ts_user a,ts_rolemenu b,ts_uservsrole c where c.userguid=a.userguid and c.roleID=b.roleID and a.userguid='" + userid + "' and b.menuGuid='" + menucode + "' ";
            DataTable dt = DB.ExecuteDataTable(sqlCommand, CommandType.Text, null);
            if (dt.Rows.Count > 0)
            {
                flag = true;
            }
            return flag;
        }

        /// <summary>
        /// 判断角色功能权限
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="menucode"></param>
        /// <returns></returns>
        public static bool CheckFun(string userid, string menucode, string cfunctioncode)
        {
            DBType dbType = OConfig.SysDBType;
            IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);
            bool flag = false;
            string sqlCommand = " select * from ts_user a,ts_roleFunction b,ts_uservsrole c where c.userguid=a.userguid and c.roleID=b.roleID and a.userguid='" + userid + "' and b.menuGuid='" + menucode + "' and b.cFunctionCode='" + cfunctioncode + "' ";
            DataTable dt = DB.ExecuteDataTable(sqlCommand, CommandType.Text, null);
            if (dt.Rows.Count > 0)
            {
                flag = true;
            }
            return flag;
        }

        /// <summary>
        /// 判断角色功能权限
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="menucode"></param>
        /// <returns></returns>
        public static bool CheckFun(string strWhere)
        {
            DBType dbType = OConfig.SysDBType;
            IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);
            bool flag = false;
            string sqlCommand = " select * from ts_user a,ts_roleFunction b,ts_uservsrole c,ts_menu d,ts_application e where c.userguid=a.userguid and c.roleID=b.roleID and b.menuGuid=d.menuguid and d.applicationGuid=e.applicationGuid  and " + strWhere;
            DataTable dt = DB.ExecuteDataTable(sqlCommand, CommandType.Text, null);
            if (dt.Rows.Count > 0)
            {
                flag = true;
            }
            return flag;
        }
    }

